package cn.pink.gatesrv;

import cn.pink.centersrv.RPCProxy;
import cn.pink.common.support.tools.node.NodeTool;
import cn.pink.core.Node;
import cn.pink.core.NodeType;
import cn.pink.core.Port;
import cn.pink.core.config.IronConfig;
import cn.pink.core.support.Log;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;

/**
 * @Author: pink
 * @Date: 2022/5/19 11:57
 */
public class GateNode extends Node {
    @Override
    public void start(Promise<Void> startPromise) {
        try {
            port = new Port(String.valueOf(Thread.currentThread().getId()));
            port.startup(this, false);

            HttpServer server = vertx.createHttpServer();

            server.connectionHandler(v -> {
                Log.gate.info("create websocket conn, ip={}", v.remoteAddress());
            });

            server.webSocketHandler(v -> {
                if (!v.path().equals(IronConfig.GATE_NET_PATH)) {
                    //拒绝WebSocket, 会触发exceptionHandler
                    v.reject();
                }

                v.textMessageHandler(vv -> {
                    RPCProxy.CenterServiceProxy proxy = RPCProxy.CenterServiceProxy.newInstance();
                    proxy.defaultHandler("wo waaaaddd");

                    proxy.listenResult((r, c) -> {
                        System.out.println(r);
                        System.out.println(c);
                    });
                });

                v.closeHandler(vv -> {
                    Log.gate.info("websocket close, ip={}", v.remoteAddress());
                });

                v.exceptionHandler(vv -> {
                    Log.gate.info("websocket exception, ip={}, cause={}", v.remoteAddress(), vv.toString());
                });
            });

            server.listen(IronConfig.GATE_NET_PORT, res -> {
                if (res.succeeded()) {
                    NodeTool.getInstance().registerNode(getId(), port.getId(), NodeType.GATE).onSuccess(v -> super.start(startPromise));
//                Log.gate.info("net server start success, listen port={}", IronConfig.GATE_NET_PORT);
                } else {
                    Log.gate.info("net server start fail, cause={}", res);
                }
            });
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        super.stop();
    }
}
